﻿--lua script

--#include "data\config\guild\Guild.lua" once 
--#include "data\config\guild\GuildContendConfig.lua" once 
--#include "data\functions\Common\RankMgr.lua" once 		--排行榜管理
----#include "data\functions\Activity\OpenServer\OpenServerGuildContendWar.lua" once
----#include "data\functions\Activity\CombineServer\CombineServerGuildContendWar.lua" once

--行会一些定时执行的函数

-- 是否行会争夺时间
function CheckContendGuildWarTime()
	local ContendSignUpTime = GuildConfig.ContendSignUpTime
	
	local nDays = System.getDaysSinceOpenServer()
	if nDays < ContendSignUpTime.openDay then
		return false
	elseif nDays == ContendSignUpTime.openDay then
		return true
	end
	
	if ContendSignUpTime.combineDay >= 0 then
		nDays = System.getDaysSinceCombineServer()
		if nDays > 0 then -- 合过服了
			if nDays < ContendSignUpTime.combineDay then
				return false
			elseif nDays == ContendSignUpTime.combineDay then
				return true
			end
		end		
	end
	
	nDays = System.getDayOfWeek()
	local state = ContendSignUpTime.weekStates[nDays + 1]
	if state == 1 then -- 攻城时间
		return true
	end	
	
	return false	-- 非攻城时间
end

--行会争夺期间
function IsContendWarStarting()
	local sdvar = System.getDyanmicVar()
	if sdvar.ContendWarStartTime and sdvar.ContendWarStartTime > 0 then
		return true
	end
	return false
end


--停止报名，去掉占领方的外观
function ContendBackAppearAndStopSign()
	if not CheckContendGuildWarTime() then return end
	local sdvar = System.getDyanmicVar()
	sdvar.ContendWarFinishTime = nil
	Guild.setContendSignState(0)
	Guild.clearContendOwnInfo()

	DeleteContendTitle()

	InitContendNpcStatueName()

	SaveContendGuildRank()
	gRankMgr_Save(RANK_CONTEND_GUILD_LIST)
end

--行会争夺战预告
function ContendGuildWarNotice()
	if not CheckContendGuildWarTime() then return end
	System.broadcastTipmsg(Lang.GuildLang.GuildContend001, ttScreenCenter) -- 将在10分钟后开启
end

--行会争夺战开始
function StartContendGuildWar()
	if not CheckContendGuildWarTime() then return end	
	local sdvar = System.getDyanmicVar()
	sdvar.ContendWarStartTime = System.getCurrMiniTime()

	Guild.startContendGuildWar()

	sdvar.ContendWarOwnerGuildId = Guild.getNextContendWarDefendGuildId()

	local pGuild = Guild.getGuild(sdvar.ContendWarOwnerGuildId)

	CreateContendStatus()
	SetNpcVisible(true)

	if pGuild then
		sdvar.ContendWarWinTime = System.getCurrMiniTime() + GuildContendConfig.ContendWinNeedSecond
		Actor.unregScriptCallback(System.getGlobalNpc(), "OnContendWin")
		Actor.regScriptTimer(System.getGlobalNpc(), 0, GuildContendConfig.ContendWinNeedSecond * 1000, GuildContendConfig.ContendWinNeedSecond * 1000, 1, "OnContendWin")
	end 	

	OnSendContendDataAll()

	local ContendSceneList = {GuildContendConfig.StatusSceenId}
	for i,v in ipairs(ContendSceneList) do
		local playerList = LuaHelp.getSceneActorListById(v) or {}
		for i2,v2 in ipairs(playerList) do
			if Actor.isSignUpContendWar(v2) then
				local playVar = Actor.getStaticVar(v2)
				if not playVar.days then playVar.days = {} end
				if not playVar.days.ContendWarState then
					Actor.triggerAchieveEvent(v2, 44, 7)
					playVar.days.ContendWarState = 1
				end
				OnContendSetDeadRelivePos(v2)
				Actor.updateActorName(v2)
			end
		end
	end

	System.broadcastTipmsg(Lang.GuildLang.GuildContend002 ,ttScreenCenter + ttChatWindow)

	changeSaveContendGuildRank()
	gRankMgr_Save(RANK_CONTEND_GUILD_LIST)
end

--进入场景
function onContendEnterScene(sysarg, sceneId, lastSceneId)
	if not CheckContendGuildWarTime() then return end	
	if not IsContendWarStarting() then
		return
	end

	if Actor.isSignUpContendWar(sysarg) and sceneId == GuildContendConfig.StatusSceenId then
		OnContendSetDeadRelivePos(sysarg)
		local sVar = Actor.getStaticVar(sysarg)
		if not sVar.days then sVar.days = {} end
		if not sVar.days.ContendWarState then
			Actor.triggerAchieveEvent(sysarg, 44, 7)
			sVar.days.ContendWarState = 1
		end	
		Actor.updateActorName(sysarg) 
		--OnSendContendData(sysarg)
		Actor.unregScriptCallback(System.getGlobalNpc(), "reEnterGuildContendScene")
		Actor.regScriptTimer(System.getGlobalNpc(), 0, GuildContendConfig.delayShowPanelTime * 1000, GuildContendConfig.delayShowPanelTime * 1000, 1, "reEnterGuildContendScene", sysarg)
				
	elseif Actor.isSignUpContendWar(sysarg) and lastSceneId == GuildContendConfig.StatusSceenId then
		Actor.updateActorName(sysarg)
		CloseActivityRightPanel( sysarg )
	end
end

--行会争夺结束
function EndContendGuildWar()
	if not CheckContendGuildWarTime() then return end	
	local sdvar = System.getDyanmicVar()

	if IsContendWarStarting() then
		Actor.unregScriptCallback(System.getGlobalNpc(), "OnContendWin")

		if sdvar.ContendWarOwnerGuildId  and sdvar.ContendWarOwnerGuildId ~= 0 then
			Guild.setContendGuildId(sdvar.ContendWarOwnerGuildId)

			System.broadcastTipmsg(string.format(Lang.GuildLang.GuildContend003, Guild.getGuildName(sdvar.ContendWarOwnerGuildId)),ttScreenCenter + ttChatWindow)
		else
			System.broadcastTipmsg(Lang.GuildLang.GuildContend004,ttScreenCenter + ttChatWindow)
		end
		sdvar.ContendWarOwnerGuildId = nil
		sdvar.ContendWarWinTime = nil
		sdvar.ContendWarFinishTime = System.getCurrMiniTime()

		Guild.endContendGuildWar()

		SendContendReward()

		local playerList = LuaHelp.getSceneActorListById(GuildContendConfig.StatusSceenId) or {}
		for k , v in ipairs(playerList) do
			if Actor.isSignUpContendWar(v) then
				OnContendSetDeadRelivePos(v)
				Actor.updateActorName(v)
				CloseActivityRightPanel( v )
			end
		end
		ClearStatusMonster()
		InitContendNpcStatueName()

		changeSaveContendGuildRank()
		gRankMgr_Save(RANK_CONTEND_GUILD_LIST)

		Guild.startContendGuildWarSign()
	end
	Guild.setContendSignState(1)
	sdvar.ContendWarStartTime = nil
	
	sdvar.guildContendTaxCanGet = 1
end


--上线 活动期间
--行会争夺时 
function OnContendActorLogin(sysarg)
	if not CheckContendGuildWarTime() then return end	
	if not IsContendWarStarting() then
		return
	end
	local sceneId = Actor.getSceneId(sysarg)
	local StatusSceenId = GuildContendConfig.StatusSceenId
	if sceneId ~= StatusSceenId then
		return
	end
	if Actor.isSignUpContendWar(sysarg) then
		OnContendSetDeadRelivePos(sysarg)
		OnSendContendData(sysarg)
		Actor.updateActorName(sysarg)
	end
end

--行会争夺时下线
function OnGuildContendLogout(sysarg)
	if not CheckContendGuildWarTime() then return end	
	if not IsContendWarStarting() then
		return
	end
	local sceneId = Actor.getSceneId(sysarg)
	local StatusSceenId = GuildContendConfig.StatusSceenId
	if sceneId ~= StatusSceenId then
		return
	end
	
	if Actor.isSignUpContendWar(sysarg) then
		OnContendSetDeadRelivePos(sysarg, true)--下线时把复活点设出去
	end
end

--设置重生点
function OnContendSetDeadRelivePos(sysarg, logout)
	local nGuildId = Actor.getGuildId(sysarg)
	local sdVar = System.getDyanmicVar()

	local relive
	if IsContendWarStarting() and GuildContendConfig.relivePosAfterEnterPalace then
		relive = GuildContendConfig.relivePosAfterEnterPalace
	elseif GuildContendConfig.relivePos then
		relive = GuildContendConfig.relivePos
	end
	if sdVar.ContendWarOwnerGuildId and sdVar.ContendWarOwnerGuildId == nGuildId and GuildContendConfig.relivePosBeforeEnterPalace then
		relive = GuildContendConfig.relivePosBeforeEnterPalace
	end 

	if logout and GuildContendConfig.relivePos then
		relive = GuildContendConfig.relivePos
	end
	if relive then
		local posX = math.min(relive[1],relive[3]) + System.getRandomNumber(math.abs(relive[3]- relive[1]) + 1)
		local posY = math.min(relive[2],relive[4]) + System.getRandomNumber(math.abs(relive[2]- relive[4]) + 1)
		Actor.SetRelivePoint(sysarg, posX, posY, relive[5], false)
	end
end 

--获取行会争夺剩余时间
function GetContendLeftTime()
	if not IsContendWarStarting() then
		return 0
	end 
	local dVar = System.getDyanmicVar()
	local nCurTime = System.getCurrMiniTime()
	local nLeftTime = (dVar.ContendWarStartTime or 0) + GuildContendConfig.ContendActivityTime - nCurTime
	return nLeftTime
end


--创建雕像
function CreateContendStatus()
	local sdvar = System.getDyanmicVar()
	local pMonster = freshSceneOneMonsterInPos(GuildContendConfig.statusMonster)
	if pMonster and sdvar.ContendWarOwnerGuildId and sdvar.ContendWarOwnerGuildId > 0 then
		local monsterName = System.getMonsterNameById(GuildContendConfig.statusMonster.monsterId) or ""
		local guildName = Guild.getGuildName(sdvar.ContendWarOwnerGuildId) or ""
		Actor.setNpcGuildId(pMonster,sdvar.ContendWarOwnerGuildId or 0)
		Actor.changeShowName( pMonster, 10, string.format(Lang.GuildLang.GuildContend006, monsterName, guildName))
	end

	return pMonster
end

function ClearStatusMonster()
	clearScenceMonster( GuildContendConfig.statusMonster )
end

--雕像死亡
function OnContendStatusDeath(monster, monId)
	if not IsContendWarStarting() then
		return
	end
	
	local cfg = GuildContendConfig.statusMonster

	if monId ~= cfg.monsterId then
		return
	end
	local sdvar = System.getDyanmicVar()

	if sdvar.onContentStatusDie == 1 then
		return
	else
		local pMonster = CreateContendStatus()
		if pMonster then
			local hp = Actor.getUIntProperty(pMonster,PROP_CREATURE_MAXHP) * 0.1
			local mp = Actor.getUIntProperty(pMonster,PROP_CREATURE_MAXMP) * 0.1
		    Actor.setUIntProperty(pMonster,PROP_CREATURE_HP,hp)
		    Actor.setUIntProperty(pMonster,PROP_CREATURE_MP,mp)
		end
	end

	sdvar.onContentStatusDie = nil
end

--雕像死亡
function OnContendStatusDie(monster, sysarg, monId)
	if not IsContendWarStarting() then
		return
	end
	
	local cfg = GuildContendConfig.statusMonster

	if monId ~= cfg.monsterId then
		return
	end
	local sdvar = System.getDyanmicVar()

	local guildId = Actor.getGuildId(sysarg)

	sdvar.ContendWarOwnerGuildId = guildId

	System.broadcastTipmsg(string.format(Lang.GuildLang.GuildContend005, Guild.getGuildName(sdvar.ContendWarOwnerGuildId) or ""), ttScreenCenter + ttChatWindow)


	sdvar.ContendWarWinTime = System.getCurrMiniTime() + GuildContendConfig.ContendWinNeedSecond
	Actor.unregScriptCallback(System.getGlobalNpc(), "OnContendWin")
	Actor.regScriptTimer(System.getGlobalNpc(), 0, GuildContendConfig.ContendWinNeedSecond * 1000, GuildContendConfig.ContendWinNeedSecond * 1000, 1, "OnContendWin")

	KillStatusChangeGuildRelivePos()

	OnSendContendDataAll()

	CreateContendStatus()

	changeSaveContendGuildRank()

	gRankMgr_Save(RANK_CONTEND_GUILD_LIST)

	sdvar.onContentStatusDie = 1
end


--重置行会出生点
function KillStatusChangeGuildRelivePos()
	local ContendSceneList = {GuildContendConfig.StatusSceenId}
	for i,v in ipairs(ContendSceneList) do
		local playerList = LuaHelp.getSceneActorListById(v) or {}
		for i2,v2 in ipairs(playerList) do
			if Actor.isSignUpContendWar(v2) then
				OnContendSetDeadRelivePos(v2)
			end
		end
	end
end


--发送行会争夺信息给所有的人
function OnSendContendDataAll()
	local ContendSceneList = {GuildContendConfig.StatusSceenId}
	for i,v in ipairs(ContendSceneList) do
		local playerList = LuaHelp.getSceneActorListById(v) or {}
		for i2,v2 in ipairs(playerList) do
			if Actor.isSignUpContendWar(v2) then
				OnSendContendData(v2)
			end
		end
	end
end

--发送行会争夺信息
function OnSendContendData(sysarg)
	local activityType 	= 1 			--活动
	local activityId 	= enRightPanelActivity_GuildContend

	local sdvar = System.getDyanmicVar()

	local panelInfo 	= {}
	panelInfo.sts 		= 1  
	panelInfo.title 	= Lang.GuildLang.GuildContendPanel001
	panelInfo.restTime 	= GetContendLeftTime()
	panelInfo.timeTitle = Lang.GuildLang.GuildContendPanel003	
	local guildName = Lang.GuildLang.GuildContendPanel006 

	if sdvar.ContendWarOwnerGuildId and sdvar.ContendWarOwnerGuildId > 0 then
		local pGuild = Guild.getGuild(sdvar.ContendWarOwnerGuildId)
		if pGuild then
			panelInfo.restTime 	= sdvar.ContendWarWinTime - System.getCurrMiniTime()
			panelInfo.timeTitle = Lang.GuildLang.GuildContendPanel002	
			guildName = Guild.getGuildName(sdvar.ContendWarOwnerGuildId)
		end
	end

	if panelInfo.restTime < 0 then
		panelInfo.restTime = 0
	end

	panelInfo.contentTitle 	= Lang.GuildLang.GuildContendPanel004  			
	panelInfo.contents 		= {}

	panelInfo.contents[1]	= string.format( Lang.GuildLang.GuildContendPanel005, guildName ) 	
		

	panelInfo.buttons   	= {}
	--panelInfo.buttons[1]	= 1							--1：退出副本，2-单倍领奖，3-双倍领奖, 4-查看排行榜

	OpenActivityRightPanel( sysarg, activityType, activityId, panelInfo )

end


function OnContendWin()
	EndContendGuildWar()
end


--npc设成可见/不可见
function SetNpcVisible(isVisible)
	--[[
	if isVisible then
		print("isVisible = true")
	else
		print("isVisible = false")
	end
	]]
	System.setNpcVisible( GuildContendConfig.StatusSceenId, GuildContendConfig.npcId, isVisible)
end

--发送行会争夺奖励
function SendContendReward()
	SendGuildContendReward()
	SendContendTitle()
end

function SendGuildContendReward(  )
	local winGuildId = Guild.getContendGuildId()
	--print("winGuildId  ="..winGuildId)
	
	local logId = LogIds.GuildContendLogId
	local logStr = Lang.LogTips.GuildContend
	local contendSceneList = {GuildContendConfig.StatusSceenId}
	for i,v in ipairs(contendSceneList) do
		local playerList = LuaHelp.getSceneActorListById(v) or {}
		for i2,v2 in ipairs(playerList) do
			local actorId = Actor.getActorId(v2)
			if winGuildId and winGuildId ~= 0 and winGuildId == Actor.getGuildId(v2) and Actor.isSignUpContendWar(v2) then
				--print("SendSbkWinGuildReward actorId2 = "..actorId)
				Awards.GiveToMailById(actorId, GuildContendConfig.winGuildAward, Lang.GuildLang.GuildContend007, Lang.GuildLang.GuildContend008, logId, logStr)
			elseif Actor.isSignUpContendWar(v2) then
				Awards.GiveToMailById(actorId, GuildContendConfig.failGuildAward, Lang.GuildLang.GuildContend009, Lang.GuildLang.GuildContend010, logId, logStr)
			end
		end
	end
end

--胜利行会称号下发
function SendContendTitle()
	local winGuildId = Guild.getContendGuildId()

	if not winGuildId then
		return
	end
	if winGuildId == 0 then
		return
	end
	local pGuild = Guild.getGuild(winGuildId)
	local guildLeaderId = Guild.getContendCityOwner()
	local onLineGuildPlayers = LuaHelp.getGuildMemberList(pGuild) or {}
	for idx,player in ipairs(onLineGuildPlayers) do
		local actorId = Actor.getActorId(player)
		--Actor.ResetShowName(player)
		if actorId == guildLeaderId then
			Actor.addTopTitle(player,GuildContendConfig.winTitleId)
		else
			local vocation = Actor.getIntProperty(player, PROP_ACTOR_VOCATION)
			for idx = 1, #GuildContendConfig.normalRoleBuffId[vocation] do
				Actor.addBuffById(player, GuildContendConfig.normalRoleBuffId[vocation][idx])
			end
		end
	end
end

--行会称号回收
function DeleteContendTitle()
	local oldWinGuildId = Guild.getOldContendGuildId()

	if not oldWinGuildId then
		--print("not exist oldWinGuildId")
		return
	end
	if oldWinGuildId == 0 then
		--print("oldWinGuildId = 0")
		return
	end

	--print("oldWinGuildId ="..oldWinGuildId)

	local pGuild = Guild.getGuild(oldWinGuildId)
	local guildLeaderId = Guild.getGuildLeaderId(oldWinGuildId)
	local onLineGuildPlayers = LuaHelp.getGuildMemberList(pGuild) or {}
	for idx,player in ipairs(onLineGuildPlayers) do
		local actorId = Actor.getActorId(player)
		--Actor.ResetShowName(player)

        if Actor.hasTopTitle(player, GuildContendConfig.winTitleId) then
            Actor.delTopTitle(player,GuildContendConfig.winTitleId)
        end

        local vocation = Actor.getIntProperty(player, PROP_ACTOR_VOCATION)
        for idx = 1, #GuildContendConfig.normalRoleBuffId[vocation] do
            if Actor.hasBuffById(player, GuildContendConfig.normalRoleBuffId[vocation][idx]) then
                Actor.delBuffById(player, GuildContendConfig.normalRoleBuffId[vocation][idx])
            end
        end
		
	end
end

--登陆玩家检测行会争夺称号
function LoginPlayerContendTitleChange(sysarg)
	local winGuildId = Guild.getContendGuildId()
	if winGuildId and winGuildId ~= 0 and winGuildId == Actor.getGuildId(sysarg) then
		local actorId = Actor.getActorId(sysarg)
		local guildOwnerId = Guild.getContendCityOwner()
        if guildOwnerId == actorId then
            if not Actor.hasTopTitle(sysarg, GuildContendConfig.winTitleId) then
                Actor.addTopTitle(sysarg,GuildContendConfig.winTitleId)
            end
        else
            local vocation = Actor.getIntProperty(sysarg, PROP_ACTOR_VOCATION)
            for idx = 1, #GuildContendConfig.normalRoleBuffId[vocation] do
                if not Actor.hasBuffById(sysarg, GuildContendConfig.normalRoleBuffId[vocation][idx]) then
                    Actor.addBuffById(sysarg, GuildContendConfig.normalRoleBuffId[vocation][idx])
                end
            end

            if Actor.hasTopTitle(sysarg, GuildContendConfig.winTitleId) then
				Actor.delTopTitle(sysarg,GuildContendConfig.winTitleId)
			end
        end
	else
		if Actor.hasTopTitle(sysarg, GuildContendConfig.winTitleId) then
			Actor.delTopTitle(sysarg,GuildContendConfig.winTitleId)
		end

		local vocation = Actor.getIntProperty(sysarg, PROP_ACTOR_VOCATION)
		for idx = 1, #GuildContendConfig.normalRoleBuffId[vocation] do
			if Actor.hasBuffById(sysarg, GuildContendConfig.normalRoleBuffId[vocation][idx]) then
				Actor.delBuffById(sysarg, GuildContendConfig.normalRoleBuffId[vocation][idx])
			end
		end
	end
end

--设置税收和npc
function OnInitContendState()
	ContendGuildTaxHandle()
	InitContendNpcStatueName()
end

--初始化城主雕像名字
function InitContendNpcStatueName()
	SetNpcVisible(false)
	local pNpc = Fuben.getNpcPtrById(GuildContendConfig.StatusSceenId,GuildContendConfig.npcId)
	if pNpc then
		local winGuildId = Guild.getContendGuildId() 
		if winGuildId and winGuildId ~= 0 then
			local guildName = Guild.getGuildName( winGuildId )
			if guildName then
				Actor.changeShowName(pNpc,10, string.format(Lang.GuildLang.GuildContend006, Lang.EntityName.n00161, guildName))
				return
			end
		end	
		Actor.changeShowName(pNpc,10, Lang.EntityName.n00161)
	end
end

function OnGuildContendChangeMember(sysarg, opType)
	if opType == 1 then
		local vocation = Actor.getIntProperty(sysarg, PROP_ACTOR_VOCATION)
		for idx = 1, #GuildContendConfig.normalRoleBuffId[vocation] do
			if not Actor.hasBuffById(sysarg, GuildContendConfig.normalRoleBuffId[vocation][idx]) then
				Actor.addBuffById(sysarg, GuildContendConfig.normalRoleBuffId[vocation][idx])
			end
		end
	elseif opType == 0 then
		local vocation = Actor.getIntProperty(sysarg, PROP_ACTOR_VOCATION)
		for idx = 1, #GuildContendConfig.normalRoleBuffId[vocation] do
			if Actor.hasBuffById(sysarg, GuildContendConfig.normalRoleBuffId[vocation][idx]) then
				Actor.delBuffById(sysarg, GuildContendConfig.normalRoleBuffId[vocation][idx])
			end
		end
	end
end

--城主变化
function OnGuildContendChangeLeader(oldContendOwnerId, newContendOwnerId)
	local oldOwner = Actor.getActorById(oldContendOwnerId)
	local newOwner = Actor.getActorById(newContendOwnerId)

	if newOwner then
		if not Actor.hasTopTitle(newOwner, GuildContendConfig.winTitleId) then
			Actor.addTopTitle(newOwner,GuildContendConfig.winTitleId)
		end
		
		local vocation = Actor.getIntProperty(newOwner, PROP_ACTOR_VOCATION)
		for idx = 1, #GuildContendConfig.normalRoleBuffId[vocation] do
			if Actor.hasBuffById(newOwner, GuildContendConfig.normalRoleBuffId[vocation][idx]) then
				Actor.delBuffById(newOwner, GuildContendConfig.normalRoleBuffId[vocation][idx])
			end
		end
	end

	if oldOwner then
		if Actor.hasTopTitle(oldOwner, GuildContendConfig.winTitleId) then
			Actor.delTopTitle(oldOwner,GuildContendConfig.winTitleId)
		end

		local vocation = Actor.getIntProperty(oldOwner, PROP_ACTOR_VOCATION)
		for idx = 1, #GuildContendConfig.normalRoleBuffId[vocation] do
			if not Actor.hasBuffById(oldOwner, GuildContendConfig.normalRoleBuffId[vocation][idx]) then
				Actor.addBuffById(oldOwner, GuildContendConfig.normalRoleBuffId[vocation][idx])
			end
		end
	end
end


--保存排行榜数据
function SaveContendGuildRank()
	local rankPtr = Ranking.getRanking(RankList[RANK_CONTEND_GUILD_LIST].strName)
	local rankCount = Ranking.getRankItemCount(rankPtr)
	local Id = rankCount + 1
	local time = System.getCurrMiniTime()


	local oldGuildId = Guild.getOldContendGuildId()
	local winGuildId = Guild.getContendGuildId()
	local guildName = Guild.getGuildName(winGuildId)
	if not guildName then
		guildName = Guild.getGuildName(oldGuildId)
	end
	if not guildName then
		guildName = ""
	end
	gRankMgr_SetRank(Id, RANK_CONTEND_GUILD_LIST, time,  guildName)

	local data = gRankMgr_GetValueByIndx(0, RANK_CONTEND_GUILD_LIST, 1)
	local myData = BaseFuc_unserialize(data)

	if not myData then
		myData = {}
	end

	local sdvar = System.getDyanmicVar()

	myData.oldGuildId = oldGuildId
	myData.winGuildId = winGuildId
	myData.ContendWarStartTime = sdvar.ContendWarStartTime
	myData.time = time
	myData.ContendWarFinishTime = sdvar.ContendWarFinishTime

	myData.ContendWarOwnerGuildId = sdvar.ContendWarOwnerGuildId
	myData.ContendWarWinTime = sdvar.ContendWarWinTime
	
	local newData = BaseFuc_serialize(myData)
	gRankMgr_SetRankEx(Id, RANK_CONTEND_GUILD_LIST, 1, newData, guildName)

end

--更改排行榜数据
function changeSaveContendGuildRank()
	local rankPtr = Ranking.getRanking(RankList[RANK_CONTEND_GUILD_LIST].strName)
	local rankCount = Ranking.getRankItemCount(rankPtr)

	local time = System.getCurrMiniTime()
	local data = gRankMgr_GetValueByIndx(0, RANK_CONTEND_GUILD_LIST, 1)
	local myData = BaseFuc_unserialize(data)

	if not myData then
		myData = {}
	end

	local Id = rankCount

	if myData and myData.time and not System.isSameDay(time, myData.time) then
		SaveContendGuildRank()
		data = gRankMgr_GetValueByIndx(0, RANK_CONTEND_GUILD_LIST, 1)
		myData = BaseFuc_unserialize(data)
		Id = rankCount + 1
	elseif Id == 0 then
		Id = 1
	end


	local oldGuildId = Guild.getOldContendGuildId()
	local winGuildId = Guild.getContendGuildId()

	local guildName = Guild.getGuildName(winGuildId)
	if not guildName then
		guildName = Guild.getGuildName(oldGuildId)
	end
	if not guildName then
		guildName = ""
	end

	local sdvar = System.getDyanmicVar()
	myData.oldGuildId = oldGuildId
	myData.winGuildId = winGuildId
	
	myData.ContendWarStartTime = sdvar.ContendWarStartTime
	myData.time = time
	myData.ContendWarFinishTime = sdvar.ContendWarFinishTime

	myData.ContendWarOwnerGuildId = sdvar.ContendWarOwnerGuildId
	myData.ContendWarWinTime = sdvar.ContendWarWinTime

	local newData = BaseFuc_serialize(myData)
	gRankMgr_SetRankEx(Id, RANK_CONTEND_GUILD_LIST, 1, newData, guildName)
end

--攻城战重启处理
function onLoadContendGuild()
	local time = System.getCurrMiniTime()
	local todayTime = System.getToday()
	local ContendSignUpTime = GuildConfig.ContendSignUpTime
	local rankPtr = Ranking.getRanking(RankList[RANK_CONTEND_GUILD_LIST].strName)
	if not rankPtr then
		loadContendGuildNoDataHandler()
		return
	end
	local rankCount = Ranking.getRankItemCount(rankPtr)
	local myData
	if rankCount > 0 then
		local data = gRankMgr_GetValueByIndx(0, RANK_CONTEND_GUILD_LIST, 1)
		myData = BaseFuc_unserialize(data)

		local sdvar = System.getDyanmicVar()
		--不到18点或者不在攻城期间
		if not CheckContendGuildWarTime() or todayTime + 18*3600 > time then
			Guild.setContendGuildId(myData.winGuildId or 0)
			Guild.setContendOldGuildId(myData.oldGuildId or 0)

			local nDays = System.getDaysSinceOpenServer()
			if nDays <= ContendSignUpTime.openDay then
				Guild.setContendSignState(0)
			else
				Guild.setContendSignState(1)
			end
			
			if ContendSignUpTime.combineDay >= 0 then
				nDays = System.getDaysSinceCombineServer()
				if nDays > 0 then -- 合过服了
					if nDays <= ContendSignUpTime.combineDay then
						Guild.setContendSignState(0)
					else
						Guild.setContendSignState(1)
					end
				end		
			end

			Guild.endContendGuildWar()
            InitContendNpcStatueName()

		--不到20点
		elseif CheckContendGuildWarTime() and todayTime + 20*3600 > time then
			if myData and myData.time and not System.isSameDay(time, myData.time) then
				Guild.setContendGuildId(myData.winGuildId or 0)
				Guild.setContendSignState(0)
				Guild.clearContendOwnInfo()

				DeleteContendTitle()

				InitContendNpcStatueName()
				SaveContendGuildRank()
				gRankMgr_Save(RANK_CONTEND_GUILD_LIST)
			else
				Guild.clearContendOwnInfo()
				Guild.setContendOldGuildId(myData.oldGuildId or 0)
			end
		elseif CheckContendGuildWarTime() and todayTime + 21*3600 > time then
			if myData and myData.time and not System.isSameDay(time, myData.time) then
				Guild.setContendGuildId(myData.winGuildId or 0)
				Guild.setContendSignState(0)
				Guild.clearContendOwnInfo()

				DeleteContendTitle()

				InitContendNpcStatueName()
				SaveContendGuildRank()

				Guild.startContendGuildWar()

                sdvar.ContendWarStartTime = todayTime + 20*3600

				sdvar.ContendWarOwnerGuildId = Guild.getNextContendWarDefendGuildId()

				local pGuild = Guild.getGuild(sdvar.ContendWarOwnerGuildId)

				CreateContendStatus()
				SetNpcVisible(true)

				if pGuild then
					sdvar.ContendWarWinTime = System.getCurrMiniTime() + GuildContendConfig.ContendWinNeedSecond
					Actor.unregScriptCallback(System.getGlobalNpc(), "OnContendWin")
					Actor.regScriptTimer(System.getGlobalNpc(), 0, GuildContendConfig.ContendWinNeedSecond * 1000, GuildContendConfig.ContendWinNeedSecond * 1000, 1, "OnContendWin")
				end 	
				changeSaveContendGuildRank()
				gRankMgr_Save(RANK_CONTEND_GUILD_LIST)
			elseif myData.ContendWarFinishTime and myData.winGuildId and myData.winGuildId > 0 then
				sdvar.ContendWarFinishTime = myData.ContendWarFinishTime
				Guild.setContendGuildId(myData.winGuildId or 0)
				Guild.setContendOldGuildId(myData.oldGuildId or 0)
				InitContendNpcStatueName()

				Guild.setContendSignState(1)

                changeSaveContendGuildRank()
                gRankMgr_Save(RANK_CONTEND_GUILD_LIST)
			else
				Guild.clearContendOwnInfo()
				Guild.setContendOldGuildId(myData.oldGuildId or 0)

				sdvar.ContendWarStartTime = todayTime + 20*3600

				sdvar.ContendWarOwnerGuildId = myData.ContendWarOwnerGuildId or Guild.getNextContendWarDefendGuildId()
				if sdvar.ContendWarOwnerGuildId and sdvar.ContendWarOwnerGuildId == 0 then
					sdvar.ContendWarOwnerGuildId = Guild.getNextContendWarDefendGuildId()
				end
				sdvar.ContendWarWinTime = myData.ContendWarWinTime or (System.getCurrMiniTime() + GuildContendConfig.ContendWinNeedSecond)

				Guild.startContendGuildWar()

				if sdvar.ContendWarWinTime <= System.getCurrMiniTime() then
					EndContendGuildWar()
				else
					CreateContendStatus()

					SetNpcVisible(true)

                    local pGuild = Guild.getGuild(sdvar.ContendWarOwnerGuildId)

					if pGuild then
						local needTime = sdvar.ContendWarWinTime - System.getCurrMiniTime()
						Actor.unregScriptCallback(System.getGlobalNpc(), "OnContendWin")
						Actor.regScriptTimer(System.getGlobalNpc(), 0, needTime * 1000, needTime * 1000, 1, "OnContendWin")
					end 
				end

				changeSaveContendGuildRank()
				gRankMgr_Save(RANK_CONTEND_GUILD_LIST)
			end
			--21点之后的处理
		elseif CheckContendGuildWarTime() and todayTime + 21*3600 <= time then
			sdvar.guildContendTaxCanGet = 1
			if myData and myData.time and not System.isSameDay(time, myData.time) then
				Guild.setContendGuildId(myData.winGuildId or 0)
				Guild.setContendOldGuildId(myData.oldGuildId or 0)
				InitContendNpcStatueName()

				Guild.setContendSignState(1)
			else
				if myData.winGuildId and myData.winGuildId > 0 then
					Guild.setContendGuildId(myData.winGuildId or 0)
					Guild.setContendOldGuildId(myData.oldGuildId or 0)
					InitContendNpcStatueName()

					Guild.setContendSignState(1)
				elseif myData.oldGuildId and myData.oldGuildId > 0 then
					Guild.setContendGuildId(myData.oldGuildId)
					InitContendNpcStatueName()
					
					Guild.setContendSignState(1)
				end
			end
		end
	else
		loadContendGuildNoDataHandler()
		return
	end
end

--没数据处理
function loadContendGuildNoDataHandler()
	local todayTime = System.getToday()
	local ContendSignUpTime = GuildConfig.ContendSignUpTime
	local sdvar = System.getDyanmicVar()
	local time = System.getCurrMiniTime()
	if not CheckContendGuildWarTime() or todayTime + 18*3600 > time then
		local nDays = System.getDaysSinceOpenServer()
		if nDays <= ContendSignUpTime.openDay then
			Guild.setContendSignState(0)
		else
			Guild.setContendSignState(1)
		end
		
		if ContendSignUpTime.combineDay >= 0 then
			nDays = System.getDaysSinceCombineServer()
			if nDays > 0 then -- 合过服了
				if nDays <= ContendSignUpTime.combineDay then
					Guild.setContendSignState(0)
				else
					Guild.setContendSignState(1)
				end
			end		
		end
	elseif CheckContendGuildWarTime() and todayTime + 20*3600 > time then
		Guild.setContendSignState(0)
		SaveContendGuildRank()
		gRankMgr_Save(RANK_CONTEND_GUILD_LIST)
	elseif CheckContendGuildWarTime() and todayTime + 21*3600 > time then
		sdvar.ContendWarStartTime = todayTime + 20*3600
		
		Guild.setContendSignState(0)

		SaveContendGuildRank()

		Guild.startContendGuildWar()

		sdvar.ContendWarOwnerGuildId = Guild.getNextContendWarDefendGuildId()

		local pGuild = Guild.getGuild(sdvar.ContendWarOwnerGuildId)

		CreateContendStatus()
		SetNpcVisible(true)

		if pGuild then
			sdvar.ContendWarWinTime = System.getCurrMiniTime() + GuildContendConfig.ContendWinNeedSecond
			Actor.unregScriptCallback(System.getGlobalNpc(), "OnContendWin")
			Actor.regScriptTimer(System.getGlobalNpc(), 0, GuildContendConfig.ContendWinNeedSecond * 1000, GuildContendConfig.ContendWinNeedSecond * 1000, 1, "OnContendWin")
		end 	
		changeSaveContendGuildRank()
		gRankMgr_Save(RANK_CONTEND_GUILD_LIST)
	elseif CheckContendGuildWarTime() and todayTime + 21*3600 <= time then
		Guild.setContendSignState(1)
	end
end


function ContendGuildTaxHandle()
	if not CheckContendGuildWarTime() then
		local dvar = System.getDyanmicVar()
		dvar.guildContendTaxCanGet = 1
		return
	end
	local var = System.getStaticVar()
	local time = System.getCurrMiniTime()
	local compTime = var.guildContendTaxRefreshTime or 0
	if System.isSameDay(compTime, time) then
		return 
	end
	var.szGuildContendTaxCanGet = var.szGuildContendTaxValue or 0
	var.szGuildContendTaxValue = 0
	var.guildContendTaxRefreshTime = time
	var.guildContendTaxGetState = 0

	local dvar = System.getDyanmicVar()
	dvar.guildContendTaxCanGet = 0
end

function GetContendGuildTax(sysarg)
	local var = System.getStaticVar()
	if var.guildContendTaxGetState == 1 then
		return false
	end
	if Guild.getContendCityOwner() ~= Actor.getActorId(sysarg) then
		return false
	end

	var.guildContendTaxGetState = 1
	Actor.addMoney( sysarg, mtBindCoin, var.szGuildContendTaxCanGet, LogIds.GuildContendTaxLogId, Lang.LogTips.GuildContendTax)
	return true
end


function reEnterGuildContendScene(NpcPtr, sysarg)
	Actor.unregScriptCallback(System.getGlobalNpc(), "reEnterGuildContendScene")
	if CheckContendGuildWarTime() and IsContendWarStarting() and Actor.isSignUpContendWar(sysarg) and Actor.getSceneId(sysarg) == GuildContendConfig.StatusSceenId then
	OnSendContendData(sysarg)
    end
end